package com.sia.springcloud.selfInspection;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author: Sirius
 * @Date: 2021/12/31 21:53
 * @Description: 心跳自检任务配置类
 * 会配置一个心跳自检任务，并开机自启
 * 注意：必须在配置文件中配置protocolName（协议名，也就是该数采微服务处理的数采协议类型，和数据库中的对应）
 **/
@Slf4j
@Component
public class SelfInspectionConfig implements ApplicationRunner {


    private static final String inspectionId = UUID.randomUUID().toString();

    @Value("${selfInspection.protocol-name}")
    private String protocolName;

    @Resource
    private Scheduler scheduler;


    @Value("${selfInspection.frequency:60}")
    private Integer frequency;


    /**
     * 配置心跳自检任务，并随系统自启
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("心跳自检：开启");

        JobDetail jobDetail = JobBuilder.newJob(SelfInspectionJob.class)
                .withIdentity(inspectionId)
                .storeDurably()
                .build();


        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.put("protocolName", protocolName);


        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        //自检频率为30秒每次，运行过程中应该设置的大一些，并且应该提供配置文件配置的方式
        scheduleBuilder.withIntervalInSeconds(frequency);
        scheduleBuilder.repeatForever();
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(inspectionId)
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }
}
